package com.liang.leetcode.dp;

/**
 * 63.不同路径 II
 */
public class Dp05_UniquePathsWithObstacles {
    public static void main(String[] args) {
        int[][] obstacleGrid = {{0, 0, 0}, {0, 1, 0}, {0, 0, 0}};
        System.out.println(uniquePaths(obstacleGrid));
    }

    /**
     * 解法1：动态规划
     */
    public static int uniquePaths(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        // dp[i][j] 表示从 (0,0) 出发，到 (i,j) 有 dp[i][j] 条不同的路径。
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            // 遇到障碍之后都是0
            if (obstacleGrid[i][0] == 1) {
                break;
            }
            // 没有障碍物则有1条路径
            dp[i][0] = 1;
        }
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] == 1) {
                break;
            }
            dp[0][j] = 1;
        }
        // 遍历
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                // 如果当前位置有障碍物，则路径数为0
                if (obstacleGrid[i][j] == 1) {
                    continue;
                }
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m - 1][n - 1];
    }

    /**
     * 空间优化
     */
    public static int uniquePaths2(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[] dp = new int[n];
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] == 1) {
                break;
            }
            dp[j] = 1;
        }
        // 遍历
        for (int i = 1; i < m; i++) {
            // 处理第一列
            if (obstacleGrid[i][0] == 1) {
                dp[0] = 0;
            }

            // 处理其他列
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] == 1) {
                    dp[j] = 0;
                } else {
                    dp[j] += dp[j - 1];
                }
            }
        }
        return dp[n - 1];
    }
}
